# -*- coding: utf-8 -*-
# File : common_util.py
# Author: taoyahui
# Date : 2021/4/5
import time
import os, sys
import configparser
from utils.path_util import get_root_dir
import logging
import datetime


cf = configparser.ConfigParser()
cf.read(os.path.join(get_root_dir(),"config.ini"))
secs = cf.sections()
vuls_path = cf.get("vuls", "root_dir")


def current_time_format():
    return time.strftime("%Y.%m.%d", time.localtime())


# 判断输入的key值是否在字典中
def has_keys(dic, *keys):
    for k in keys:
        if k not in dic.keys():
            return False
    return True


# 获取目录下的所有文件，并按照时间先后排序
def get_file_list(file_path):
    dir_list = os.listdir(file_path)
    dir_list.sort(key=lambda fn: os.path.getmtime(file_path+'/'+fn))
    return dir_list


# 获取当前时间的时间戳(int类型)
def get_current_timestamp():
    return int(time.time())


# 当前时间转换为字符串穿类型
def time_str_format():
    """
    当前时间转换为字符串穿类型
    :return:
    """
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


def specify_time_format(time_input):
    """
    将时间转为指定格式的字符串
    :param time_input:
    :return:
    """
    return time_input.strftime('%Y-%m-%d %H:%M:%S %f')


def str_to_time_format(time_input):
    """
    将时间转为指定格式的字符串
    :param time_input:
    :return:
    """
    return datetime.datetime.strptime(time_input, '%Y-%m-%dT%H:%M:%S.000Z')


# 将格式为HH:ss的字符串转为时间后取分(min)和秒(sec), e.g "22:22" -> tm_min: 22, tm_sec: 22
def time_hour_min_format(time_str):
    parse_time = time.strptime(time_str, "%H:%M")
    tm_hour = parse_time.tm_hour
    tm_min = parse_time.tm_min
    return tm_hour, tm_min


# 生成错误日志内容
def gen_error_msg(func_name, exception_log):
    return f"Error:[{time_str_format()}] Function name is -->{func_name}, Log is --> {exception_log}"


def get_latest_file_path(target_path, hostname=None):
    res = os.listdir(target_path)
    path_list = []
    for dir in res:
        file_path = os.path.join(target_path, dir,f"{hostname}.json")
        if os.path.exists(file_path):
            path_list.append(file_path)
    if len(path_list) == 0:
        return 0
    path_list.sort(key=lambda f: os.path.getmtime(f))

    return path_list[-1]


def get_log_path():
    log_dir_path = os.path.join(get_root_dir(), "log")
    if not os.path.exists(log_dir_path):
        os.mkdir(log_dir_path)
    log_patch = os.path.join(log_dir_path, "{time}.txt")
    return log_patch


def get_logger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    log_path = os.path.join(get_root_dir(), "log")
    if not os.path.exists(log_path):
        os.mkdir(log_path)
    handler =  logging.FileHandler(f"{log_path}/{time.strftime('%Y-%m-%d', time.localtime())}.txt")
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


def gen_modify_res(code, data):
    return {
        'code': code,
        'data': data
    }


def week_chinese_to_int(parse_str):
    """
    将中文的星期转为数字 , e.g 周一:0  周二:1
    :param parse_str:
    :return:
    """
    if parse_str == '周一':
        return 0
    elif parse_str == '周二':
        return 1
    elif parse_str == '周三':
        return 2
    elif parse_str == '周四':
        return 3
    elif parse_str == '周五':
        return 4
    elif parse_str == '周六':
        return 5
    else:
        return 6



if __name__ == '__main__':
    # file_path = '/Users/taoyahui/Downloads/vulsctl/docker/results'
    # print(get_file_list(file_path))
    # print(time_hour_min_format('22:33'))
    # logger = get_logger(__file__)
    # logger.info("jsdfjdskfjskfdj")
    import datetime
    print("192.168.50.1".replace(".","_"))


    # datetime_str = "2021-07-11T05:01:06.000Z"
    # # import datetime
    # t = datetime.datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.000Z')
    # print(datetime.hour)
    # print(datetime.minute)
    # print(type(datetime.datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.000Z')))